package wootop.rabbitmq.transformation.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wootop.rabbitmq.transformation.pojo.RealData;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author AZHE_SUN
 * @date 2021-4-7 16:42
 **/
@Component
public class RawEcgReceiver {


    @Autowired
    public RabbitTemplate rabbitTemplate;

    /**
     * 偶数用户的路由
     *
     * @param message
     * @throws
     * @throws InterruptedException
     */
    @RabbitHandler
    @RabbitListener(queues = "#{deptQueue}")
    public void evenData(byte[] data, Channel channel, Message message) throws IOException {
        try {
            System.out.println("开始时间："+System.currentTimeMillis());
            message.getBody().toString();
            MessageConverter converter = new Jackson2JsonMessageConverter();
            List<Map<String,Object>> realData = (List)converter.fromMessage(message);
//            System.out.println(realData);
            //消息确认
            System.out.println("结束时间："+System.currentTimeMillis());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //失败后消息被确认
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            e.printStackTrace();
        }
    }
    /**
     * 数组转对象
     * @param bytes
     * @return
     */
    public Object toObject (byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
            ObjectInputStream ois = new ObjectInputStream (bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
}
